<?php
/*
// @author : lael
// blog : http://hi.baidu.com/lael80
// http://www.gzyd.net
// all right reserved.
*/

namespace ydsdk\controllers;

class api extends \ydsdk\core\api {
	public function __construct(){
		parent::__construct();
	}

	public function sign()
	{
		$phone     = $_POST['phone'];
		$token     = $_POST['token'];
		if(!$phone){
            exit(json_encode(array(
                'status'    => -2,
                'msg'       => '参数不得为空'
            )));
        }
        $student = $this->model('student');
       // $sinfo = $this->db->get_row('deerxi_student','*',array('parentsphone '=>$phone));
       $res = $student->get_by_phone($phone);
       if(!$res)
       {
        	exit(json_encode(array(
	                'status'    => -3,
	                'msg'       => '手机号码不正确'
	            )));
       }
        exit(json_encode(array(
                'status'    => 0,
                'msg'       => '成功',
                'data'=>$res
       )));
        
	}

    public function push()
    {
    	//log_message($_FILES);
        $upload_data = $this->uploads();
		//log_message($upload_data);
        $pic = $upload_data['headerimg']['filename'];
        $iccode     = $_POST['iccode'];
        $device_id  = $_POST['device_id'];
        $type  = empty($_POST['type'])?1:$_POST['type']; //老师或学生，1学生；2老师
        
        if(!$iccode || !$device_id){// || !$pic){
            exit(json_encode(array(
                'status'    => -2,
                'msg'       => '参数不得为空'
            )));
        }
        
        $student = $this->model('student');
        $sinfo = $student->get_full_by_iccode($iccode);
         
         
        if(!$sinfo)
        {
        	$sinfo = $this->db->get_row('deerxi_teacher','*',array('iccode '=>$iccode));
        }
		$common = $this->model('common');
        $school = $common->get_config($sinfo['sid']);
       
		if(!$sinfo){
		exit(json_encode(array(
	                'status'    => -3,
	                'msg'       => 'IC卡不合法'
	            )));
		}
        $data = array();
        $data['sid'] = $sinfo['id'];
        $data['device_id'] = $device_id;
        $data['add_time'] = time();
        $data['times'] = date('Y-m-d');
        $data['pic'] = checknull($pic);
        $data['token'] = $school['wx_token'];
        $data['iccode'] = $iccode;
        $data['type'] = $type;
        if($this->db->insert('deerxi_shuttle',$data)){
            //记录推送消息
            $shulleid = $this->db->insert_id();
            if($shulleid)
            {
            	$stats = $this->model('stats');
            	$cid = $sinfo['cid'];
            	if($type==2)$cid = 0;
            	 //$stats->class_stats($cid,$sinfo['sid'],$iccode);
            	//var_dump($iccode);
            	$stats->class_stats2($cid,$sinfo['sid'],$iccode);
            }
            if($type!=2)
				$userinfo = $this->db->get_row('deerxi_user','*',array('id'=>$sinfo['parid']));
			else
				$userinfo=$sinfo;
	   
            if($type==1)
            {
            	//发送短信通知
            	if($type!=2){
					$phone = $sinfo['sms_phone'];//$common->get_sms_phone($sinfo['sid'],$sinfo['id']);
					if(!empty($phone)&&$sinfo['is_sms']==1)
					{
						$param = array('name'=>$sinfo['name'],'time'=> date('Y-m-d H:i:s',time()),'school'=>$school['name']);
						$common->send_check_sms($phone,$sinfo['sid'],$param);
					}
				}else{
					$phone=$sinfo['phone'];
					if(!empty($phone)){
						$param = array('name'=>$sinfo['name'],'time'=> date('Y-m-d H:i:s',time()),'school'=>$school['name']);
						$common->send_check_sms($phone,$sinfo['sid'],$param);
					}
				}
            	//发送微信通知
            	$user = $this->model('user');
            	$res = $user->get_list_friend($userinfo['id'],1);
            	 
            	if(!empty($res)){
	            	foreach($res as $v)
	            	{
	            		$common->shuttletmpl($v['openid'],$shulleid,$school);
	            	}
            	}
            	
            }
           
            exit(json_encode(array(
                'status'    => 0,
                'msg'       => '成功'
            )));
        }else{
            exit(json_encode(array(
                'status'    => -1,
                'msg'       => '失败'
            )));
        };
    }

    public function getrecord(){
        $iccode=$_POST['iccode'];
        $page=$_POST["page"];
        $pagesize=$_POST["pagesize"];
        $month=$_POST["month"];
        $sign=$_POST["sign"];
        if($sign!=md5("xiaoxuntong")) exit(json_encode(array('status'=> 0,'msg'=>'签名错误')));
        if(empty($page)) $page=1;
        if(empty($pagesize)) $pagesize=20;
        $offset=($page-1)*$pagesize;
        $where="";
        if($month){
            $start=strtotime($month."-01");
            $end= strtotime("+1 month -1 day",$start);
            $where=" and add_time>=$start and add_time<$end";
        }
        if(empty($iccode)){
            exit(json_encode(array('status'=> 0,'msg'=>'缺少参数')));
        }
        $list=$this->db->select("select concat('".siteurl()."',pic) as pic,iccode,device_id,sid,FROM_UNIXTIME(add_time) as add_time from ##deerxi_shuttle where iccode=$iccode $where order by add_time desc limit $offset,$pagesize");
        exit(json_encode(array('status'=> 1,'msg'=>'成功','data'=>$list)));
    }

    public function geo()
    {
        $lng    = $_POST['lng'];
        $lat    = $_POST['lat'];
        $device_id  = $_POST['device_id'];
        
        
        if (!$lng || !$lat || !$device_id) {
            exit(json_encode(array(
                'status'    => -2,
                'msg'       => '参数不得为空'
            )));
        }
        if($this->db->insert('geo',array(
            'token'     => 'ca39f511a25814c9475f6e5f952f9d89',
            'device_id' => $device_id,
            'lat'       => $lat,
            'lng'       => $lng,
            'addtime'   => date('Y-m-d H:i:s')
        ))){
            exit(json_encode(array(
                'status'    => 0,
                'msg'       => '成功'
            )));
        }else{
            exit(json_encode(array(
                'status'    => -1,
                'msg'       => '失败'
            )));
        };
    }

    public function getstatus(){
        $page = $_POST['page']?$_POST['page']:1;
        $perPage = $_POST['perPage']?$_POST['perPage']:80;
        //$limit = $perPage*($page-1).",".$perPage;
        $device_id = $_POST['device_id'];
        //die(json_encode($_POST));
        if(empty($device_id)){
            exit(json_encode(array(
                'status'    => -2,
                'data'       => '非法请求'
            )));
        }
        $school = $this->db->get_row('deerxi_device','*',array('device_id'=>$device_id));
        $countpage = $this->db->get_count('deerxi_student', array('sid'=>$school['admin_id']));
        $countperpage = ceil($countpage/$perPage);
        $sql = 'select id,sex,name,code,iccode,parents,parentsphone,cid,1 as type  from ##deerxi_student where sid='.$school['admin_id'].' limit '.$perPage*($page-1).','.$perPage.'';
        $data = $this->db->select($sql);
        foreach($data as $key =>$v)
        {
        	$ic_sql = 'select stu_id, iccode,1 as type  from ##stu_iccode where stu_id='.$v['id'].'';
        	$res = $this->db->select($ic_sql);
        	$data[$key]['iccodes'] = $res;
        }
        $teacher = array();
        if($countperpage==$page)
        {
        	$sql = 'select id,0 as sex,name,0 as code,iccode,0 as parents,0 as parentsphone,cid,2 as type from ##deerxi_teacher where   sid='.$school['admin_id'].'  ';
        	$teacher = $this->db->select($sql);
        	foreach($teacher as $key =>$v)
	        {
	        	$teacher[$key]['iccodes'] = array(array('stu_id'=>$v['id'],'iccode'=>$v['iccode'],'type'=>2));
	        }
        	$data = array_merge($data, $teacher); 
        }
        if($data){
            exit(json_encode(array(
                'status'    => 0,
                'countpage' => $countperpage,
                'data'       => $data
            )));
        }else{
            exit(json_encode(array(
                'status'    => -1,
                'data'       => '没有数据'
            )));
        }
    }


    public function getclass(){
        $page = !empty($_POST['page'])?$_POST['page']:1;
        $device_id = $_POST['device_id'];
        if(!$device_id){
            exit(json_encode(array(
                'status'    => -2,
                'data'       => '非法请求'
            )));
        }
        $school = $this->db->get_row('deerxi_device','*',array('device_id'=>$device_id));  
        $data = $this->db->select('deerxi_classes', '*', array('sid'=>$school['admin_id']));

        if($data){
            exit(json_encode(array(
                'status'    => 0,
                'data'       => $data
            )));
        }else{
            exit(json_encode(array(
                'status'    => -1,
                'data'       => '没有数据'
            )));
        }
    }


    /*
     * 获取学校的相关信息
     * */
    public function getSchool(){
        $device_id =  $_POST['device_id'];
        $contenttype = $_POST['contenttype'];
        if(!$device_id){
            exit(json_encode(array(
                'status'    => -2,
                'data'       => '非法请求'
            )));
        }
        $device = $this->db->get_row('deerxi_device','*',array("device_id" => $device_id));
        if(!$device['admin_id']){
            exit(json_encode(array(
                'status'    => -2,
                'data'       => '非法请求'
            )));
        }
        $school = $this->db->get_row('admin','*',array('admin_id' => $device['admin_id']));
        $data = array();
        $data['admin_id'] = $school['admin_id'];
        $data['email'] = $school['email'];
        $data['address'] = $school['address'];
        $data['name'] = $school['name'];
        $data['gname'] = $school['gname'];
        $data['phone'] = $school['phone'];
        $data['logo'] = $school['logo'];
        $data['receive_time'] = '0800';   //接小孩子时间点
        $data['send_start'] = '0700';
        $data['send_end'] = '0800';
        $data['receive_start'] = '1500';
        $data['receive_end'] = '1800';
		$data['video'] = siteurl().$school['video'];
		$data['banner'] = array_filter(explode("\n", str_replace("\r", "", $school['banner'])));
		foreach($data['banner'] as &$v){
			$v = siteurl().$v;
		}
		unset($v);
         
        if($contenttype ==1){
            $data['contentURL'] = siteurl(array('con' => 'api/content', 'device_id' => $device_id, 'contenttype' => 1));
        }else{
            $data['contentURL'] = siteurl(array('con' => 'api/content', 'device_id' => $device_id, 'contenttype' => 2));
        }

        if($school){
            exit(json_encode(array(
                'status'    => 0,
                'data'       => $data
            )));
        }else{
            exit(json_encode(array(
                'status'    => -1,
                'data'       => '没有数据'
            )));
        }

    }
	
	public function getNotice(){
        $device_id =  $_POST['device_id'];
        if(!$device_id){
            exit(json_encode(array(
                'status'    => -2,
                'data'       => '非法请求'
            )));
        }
        $device = $this->db->get_row('deerxi_device','*',array("device_id" => $device_id));
        if(!$device['admin_id']){
            exit(json_encode(array(
                'status'    => -2,
                'data'       => '非法请求'
            )));
        }
		$list = $this->db->get_arr('deerxi_notice', 'id,title,info,add_time', 'sid='.$device['admin_id'].' order by id desc limit 0,5');
        if($list){
            exit(json_encode(array(
                'status'    => 0,
                'data'       => $list
            )));
        }else{
            exit(json_encode(array(
                'status'    => -1,
                'data'       => '没有数据'
            )));
        }
	}

    public function content(){
        $device_id = $_POST['device_id'];
        $type = $_POST['contenttype'];
        $device = $this->db->get_row('deerxi_device','*',array('device_id'=>$device_id));
        if($type == 1){
            $data['content'] = $device['content1'];
        }else{
            $data['content'] = $device['content2'];
        }
		exit(json_encode(array(
			'status'    => 0,
			'data'       => $data
		)));
    }
	
	public function macpos(){
		$pos['macno']=$_POST["macno"];
		$pos['latitude']=$_POST["latitude"];
		$pos['longitude']=$_POST["longitude"];
		$pos['ltime']=time();
		$url="http://api.map.baidu.com/ag/coord/convert?from=0&to=4&x=".$pos['longitude']."&y=".$pos['latitude'];
		$ret = json_decode(file_get_contents($url));
		if($ret->error==0){
			$pos['latitude']=base64_decode($ret->y);
			$pos['longitude']=base64_decode($ret->x);
		}
		$this->db->insert("m_record",$pos);
		$this->db->replace("m_list",$pos);
		exit(json_encode(array(
			'status'    => 0,
			'data'       => array()
		)));
	}
}
